<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { CheckboxValueType } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  options: {
    type: Array,
    default: () => []
  },
  multiple:{
    type: Boolean,
    default: () => true
  }
})

const emits = defineEmits(["update:modelValue", "change"]);

const innerValue = computed({
  get: () => props.modelValue,
  set: (newValue) => {
    emits("update:modelValue", newValue);
  },
});


const checkAll = ref(false)
const indeterminate = ref(false)


watch(innerValue, (val) => {
  if (val.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (val.length === props.options.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
})

const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false
  if (val) {
    innerValue.value = props.options.map((_) => _.id)
  } else {
    innerValue.value = []
  }
  
}
const handleCheckedChange = (value) => {

 
  emits('change', value)
}
</script>

<template>
 
  <el-select
    v-model="innerValue"
    :multiple="multiple"
    collapse-tags
    :max-collapse-tags="3"
    clearable
    filterable
    placeholder="Select"
    @change="handleCheckedChange"
  >
    <template #header v-if="multiple==true">
      <el-checkbox 
        v-model="checkAll"
        :indeterminate="indeterminate"
        @change="handleCheckAll"
      >
        All
      </el-checkbox>
    </template>
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.value"
      :value="item.id"
    />
  </el-select>
</template>

<style scoped lang="scss">

</style>
